from Account import *
from Category import *
from Record import *
from Statistic import *
from Budget import *
from Currency import *
from Common import *
from Users import *
import GlobalData
import threading

class UIService:
    def __init__(self, logger, service_map):
        self.logger = logger
        self.service_map = service_map

    def addRecord(self, args):
        account = self.service_map['account'].getAllGroupedByCurrency({})
        income_cat = self.service_map['category'].getIncome({})
        payment_cat = self.service_map['category'].getPayment({})
        transfer_cat = self.service_map['category'].getTransfer({})
        users = self.service_map['users'].getAll({})
        ret = {
            'account': account, 'income_cat': income_cat, 'payment_cat': payment_cat, 
            'transfer_cat': transfer_cat, 'users': users
        }
        return makeReturn(Error.SUCCESS, ret)

    def records(self, args):
        # 这两个页面所需的内容一样
        return self.addRecord(args)

    def statistic(self):
        pass

    def budget(self):
        pass

    def management(self):
        pass

class KeepAccountServices:
    '''统一初始化所有的Service
    统一所有service请求的入口'''
    def __init__(self, logger):
        # global_data最先初始化
        self.global_data = GlobalData.GlobalData(logger)
        self.global_data.load_data()

        self.service_lock = threading.Lock()
        self.service_map = {
            'account':      Account(logger, self.global_data),
            'budget':       Budget(logger, self.global_data),
            'category':     Category(logger, self.global_data),
            'currency':     Currency(logger, self.global_data),
            'record':       Record(logger, self.global_data),
            'statistic':    Statistic(logger, self.global_data),
            'users':        Users(logger, self.global_data)
        }
        self.ui_service = UIService(logger, self.service_map)

    def handleRequest(self, service_name, method_name, args):
        if service_name == 'ui':
            service = self.ui_service
        else:
            if service_name not in self.service_map:
                return makeReturn(Error.ILLEGAL_URL, 'service not exist!')
            service = self.service_map[service_name]
        self.service_lock.acquire()
        if hasattr(service, method_name) == False:
            ret = makeReturn(Error.METHOD_NOT_EXIST)
        else:
            ret = getattr(service, method_name)(args)
        self.service_lock.release()
        return ret
